<template>
  <el-dialog :visible.sync="visible" width="957px"
             :title="!dataForm.id ? $t('add') : $t('update')"
             :close-on-click-modal="false"
             @close="closeHanler"
             :close-on-press-escape="false">
    <el-form :model="dataForm"
             :rules="dataRule"
             ref="dataForm"
             @keyup.enter.native="dataFormSubmitHandle()"
             label-width="120px">
      <el-form-item prop="name"
                    :label="$t('role.name')" style="margin-bottom: 23px;">
        <el-input v-model="dataForm.name"
                  :placeholder="$t('role.name')"></el-input>
      </el-form-item>
      <el-form-item prop="remark"
                    :label="$t('role.remark')" style="margin-bottom: 23px;">
        <el-input v-model="dataForm.remark"
                  :placeholder="$t('role.remark')"></el-input>
      </el-form-item>
      <el-form-item prop="roleIdList"
                    :label="$t('role.roleList')" style="margin-bottom: 23px;">
        <el-select v-model="dataForm.roleIdList"
                       multiple
                       collapse-tags
                       clearable
                       style="width: 300px;"
                       :placeholder="$t('role.roleList')">
              <el-option v-for="(role,index) in roleList"
                         :key="index"
                         :label="role.name"
                         :value="role.id"></el-option>
            </el-select>
      </el-form-item>
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="Menu Scope" name="menuscope">
          <el-tree :data="menuList" v-loading="loading"
                            @check="checkChange"
                           :props="{ label: 'name', children: 'children' }"
                           node-key="id"
                           ref="menuListTree"
                           accordion
                           :check-strictly="true"
                           show-checkbox>
                  </el-tree>
        </el-tab-pane>
        <el-tab-pane label="Assets Scope" name="assetsscope" >
          <AssetsScope v-if="visible" ref="AssetsScope" :FatheractiveName="activeName" :loading2.sync="loading2" :isDisabled.sync="isDisabled" :roleId="dataForm.id"></AssetsScope>
        </el-tab-pane>
      </el-tabs>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false" :disabled="loading||loading2 ||isDisabled"
                 size="small">{{ $t('cancel') }}</el-button>
      <el-button type="primary"
                 size="small" :disabled="loading||loading2 ||isDisabled"
                 @click="dataFormSubmitHandle()">{{ $t('confirm') }}</el-button>
    </template>
  </el-dialog>
</template>

<script>
import { debounce } from 'lodash'
import AssetsScope from './assets-scope.vue'
export default {
  components: {
    AssetsScope
  },
  provide () {
    return {
      isDefaultRole: () => true
    }
  },
  data () {
    return {
      visible: false,
      menuList: [],
      dataForm: {
        id: '',
        name: '',
        menuIdList: [],
        remark: '',
        roleIdList: []
      },
      roleList: [],
      permissionList: [],
      activeName: 'menuscope',
      loading: false,
      loading2: false,
      isDisabled: false
    }
  },
  computed: {
    dataRule () {
      return {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleClick(val) {
      this.$refs.AssetsScope.handleClick()
    },
    init () {
      this.loading = true
      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        this.$refs.menuListTree.setCheckedKeys([])
        Promise.all([
          this.getMenuList(),
          this.getRoleList()
        ]).then(() => {
          if (this.dataForm.id) {
            this.getInfo()
          }
        }).finally(() => {
          this.loading = false
        })
      })
    },
    getMenuList () {
      return this.$interface.system.getMenuSelectApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.menuList = res.data
        }).catch(() => { })
    },
    getRoleList () {
      return this.$interface.system.getDefaultRoleListApi()
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.roleList = res.data
        }).catch(() => { })
    },
    setRuleList () {
      if (this.roleList.length > 0) {
        this.dataForm.roleIdList = this.dataForm.roleIdList.filter(e => this.roleList.findIndex(o => o.id === e) > -1)
      } else {
        setTimeout(() => {
          this.setRuleList()
        }, 800)
      }
    },
    getInfo () {
      this.$interface.system.getTenantRoleInfoApi(this.dataForm.id)
        .then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.dataForm = {
            ...this.dataForm,
            ...res.data
          }
          this.dataForm.menuIdList.forEach(item => this.$refs.menuListTree.setChecked(item, true))
          this.setRuleList()
        }).catch(() => { })
    },
    dataFormSubmitHandle: debounce(function () {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false
        }
        this.dataForm.menuIdList = [
          ...this.$refs.menuListTree.getHalfCheckedKeys(),
          ...this.$refs.menuListTree.getCheckedKeys()
        ]
        this.dataForm.permissionList = this.permissionList
        if(this.$refs.AssetsScope){
          this.dataForm = {
            ...this.dataForm,
            assetsSave:this.$refs.AssetsScope.getValue()
          }
          delete this.dataForm.assets
        }
        this.loading = true
        this.loading2 = true
        const changeTenantRole = () => {
          if (!this.dataForm.id) {
            return this.$interface.system.postTenantRole(this.dataForm)
          } else {
            return this.$interface.system.putTenantRole(this.dataForm)
          }
        }
        var changeDefaultRule = {
          url: '/DefaultRole',
          username: this.$store.state.user.id,
          email: this.$store.state.user.email
        }
        this.$interface.um.poststatRouteAPI(changeDefaultRule)
        changeTenantRole().then(({ data: res }) => {
          this.$nextTick(()=>{
            this.loading = false
            this.loading2 = false
          })
          if (res.code !== 0) {
            if(res.code === 10052) {
              return this.$showErrorWithAssetList(res)
            }
            return this.$message.error(res.msg)
          }
          this.$message({
            message: this.$t('prompt.success'),
            type: 'success',
            duration: 500,
            onClose: () => {
              this.visible = false
              this.$emit('refreshDataList')
            }
          })
        }).catch(() => { 
          this.loading = false
          this.loading2 = false
        })
      })
    }, 1000, { 'leading': true, 'trailing': false }),
    checkChange (val, aa, bb) {
      if (val.permissions) {
        if (this.permissionList.includes(val.permissions)) {
          let index = this.permissionList.findIndex(i => i === val.permissions)
          this.permissionList.splice(index, 1)
        } else {
          this.permissionList.push(val.permissions)
        }
      }
    },
    closeHanler () {
      this.permissionList = []
      // if(this.$refs.AssetsScope){
      //   this.$refs.AssetsScope.reset()
      // }
      Object.assign(this.$data, this.$options.data()) 
    }
  }
}
</script>
